package com.cuc.platform.core.componet.security;

import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;

public class CustomCredentialsMatcher extends SimpleCredentialsMatcher {  
	  
    @Override  
    public boolean doCredentialsMatch(AuthenticationToken token,  
            AuthenticationInfo info) {  
        Object tokenCredentials = encrypt(toBytes(token.getCredentials()));  
        Object accountCredentials = getCredentials(info);  
        return equals(tokenCredentials, accountCredentials);  
    }  
  
    private byte[] encrypt(byte[] data) {  
        try {  
            byte[] key = "11111111".getBytes();  
  
            // DES算法要求有一个可信任的随机数源  
  
            SecureRandom sr = new SecureRandom();  
  
            // 从原始密钥数据创建DESKeySpec对象  
            DESKeySpec dks = new DESKeySpec(key);  
  
            // 创建一个密匙工厂，然后用它把DESKeySpec转换成  
  
            // 一个SecretKey对象  
  
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");  
  
            SecretKey secretKey = keyFactory.generateSecret(dks);  
  
            // using DES in ECB mode  
  
            Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");  
  
            // 用密匙初始化Cipher对象  
  
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, sr);  
  
            // 执行加密操作  
  
            byte encryptedData[] = cipher.doFinal(data);  
  
            return encryptedData;  
  
        } catch (Exception e) {  
  
            System.err.println("DES算法，加密数据出错!");  
  
            e.printStackTrace();  
  
        }  
        return null;  
    }  
}  